package com.yb.guigu.pick.web.handler;

import com.yb.guigu.pick.core.bean.GuiguResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;

/**
 * Copyright (C), 2022-2022, 姚兵
 * Author: 32210
 * Date: 2022/11/13 21:27
 * FileName: ErrorController
 * Description:
 */

@RestController
@Slf4j
public class ErrorControllerHandler implements ErrorController {

    @RequestMapping("${server.error.path:${error.path:/error}}")
    public ResponseEntity<GuiguResult> error(Exception e, HttpServletRequest request){
        log.error("error:{}",e);
        HttpStatus status = getStatus(request);
        log.info("status:{}",status);
        return ResponseEntity.status(status).body(GuiguResult.error(status.value(),status.getReasonPhrase()));
    }

    protected HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);

        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        try {
            return HttpStatus.valueOf(statusCode);
        }
        catch (Exception ex) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }
}
